package com.example.controller;

import com.example.entity.Student;
import com.example.entity.Teacher;
import com.example.service.ExampleService;
import com.example.vo.StudentParam;
import com.example.vo.StudentVo;
import xyz.lwm.lazycat.annotation.Inject;
import xyz.lwm.lazycat.annotation.Value;
import xyz.lwm.lazycat.utility.R;
import xyz.lwm.lazycat.utility.convert.Convert;
import xyz.lwm.lazycat.web.Controllable;
import xyz.lwm.lazycat.web.annocation.Controller;
import xyz.lwm.lazycat.web.annocation.Form;
import xyz.lwm.lazycat.web.annocation.Get;
import xyz.lwm.lazycat.web.annocation.PathParam;
import xyz.lwm.lazycat.web.annocation.Post;
import xyz.lwm.lazycat.web.annocation.Produces;
import xyz.lwm.lazycat.web.route.Router;

import java.util.List;

/**
 * {@link Controller} 的 value 是 path 的前段; <br>
 * {@link Controllable} 接口可以直接添加路由; <br>
 * 所有的路由返回的对象会自动转为 json, 参考 {@link Produces}
 *
 * @author lwm
 */
@Controller("example")
public class ExampleController implements Controllable {

    // 注入 ExampleService
    @Inject
    private ExampleService exampleService;

    // 注入 server.port 配置, 无则返回 1111
    @Value("${server.port : 1111}")
    private int port;

    // 注入 web.static.index2 配置, 无则返回 index.html
    @Value("${web.static.index2:  http://localhost:8090  }")
    private String index2;

    // 通过该方法直接添加路由
    @Override
    public void control(Router router) {
        // 注意: 此处添加 path 与 @Controller 等注解无关; 这是原始用法
        router.get("teachers", ctx -> {
            List<Teacher> teachers = exampleService.getTeacherList();
            ctx.json(R.ok(teachers));
        });
        router.get("teachers/{teacherId}", ctx -> {
            String teacherId = ctx.req().getPathParam("teacherId");
            Long id = Convert.to(teacherId, Long.class);
            Teacher teacher = exampleService.getTeacherById(id);
            ctx.json(R.ok(teacher));
        });
        router.before("example/students/**", ctx -> {
            System.out.println("before students");
        });
    }

    // GET / POST 等注解会解析成路由
    @Get("students")
    public R<List<Student>> getStudents() {
        return R.ok(exampleService.getStudentList());
    }

    // @PathParam("id") 会读取 path 中的 {id} 参数
    @Get("students/{id}")
    public R<Student> getStudentById(@PathParam("id") Long id) {
        return R.ok(exampleService.getStudentById(id));
    }

    // @Form 会将表单参数解析成对象
    // @Body 会将 json string 解析成对象
    @Post("students")
    public R<List<StudentVo>> getStudentsBy(@Form StudentParam param) {
        return R.ok(exampleService.getStudentsBy(param));
    }

}
